<template>
  <div class="table">
    <div class="container">
      <div class="handle-box" >
        <!--<el-button type="primary" size="mini" @click="delAll">批量删除</el-button>-->
        <!--<el-input v-model="select_word" size="mini" placeholder="筛选相关用户" class="handle-input"></el-input>-->
        <el-button type="primary" size="mini" @click="centerDialogVisible = true">添加新课程</el-button>
      </div>
    </div>
    <el-table class="el-table_p" size="mini" ref="multipleTable" border :data="courseList" :header-cell-style="{background:'#f4f3f9',color:'black',}"  >
      <!--<el-table-column type="selection" ></el-table-column>-->
      <el-table-column width="80" prop="num" label="序号" align="center"></el-table-column>

      <el-table-column prop="createDate" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="name" label="课程名称" align="center"></el-table-column>
      <el-table-column prop="code" label="课程码" align="center" width="245px"></el-table-column>
      <el-table-column prop="term" label="学期（天）" align="center"></el-table-column>
      <el-table-column prop="amount" label="课程金额（元）" align="center" width="110px"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="{row}">
          {{row.status == 0||row.status == '启用'?"启用":"禁用"}}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" align="center" width="150px">
      </el-table-column>
      <el-table-column prop="parentOperate" label="监护" align="center" width="140px">
      </el-table-column>
      <el-table-column prop="method" label="方式" align="center" ></el-table-column>
      <el-table-column label="操作" align="center" width="240px">
        <!-- <template slot-scope="scope" v-if="level==0"> -->
        <template slot-scope="scope" >
          <el-button size="mini" class="template_btn" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" class="template_btn" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" class="template_btn" type="success" @click="handleBinding(scope.row)">绑定</el-button>

        </template>
      </el-table-column>
    </el-table>
    <!--<div class="pagination">-->
    <!--<el-pagination-->
    <!--background-->
    <!--layout = "total,prev,pager,next"-->
    <!--:current-page="currentPage"-->
    <!--:page-size="pageSize"-->
    <!--:total="tableData.length"-->
    <!--@current-change="handleCurrentChange"-->
    <!--&gt;-->
    <!--</el-pagination>-->
    <!--</div>-->
    <el-dialog title="课程绑定方案" :visible.sync="bindVisible" width="400px" center>
      <div >
        <el-checkbox-group v-model="checkList" @change="changeBtn">
          <template v-for="(item,index) in planList">
            <el-checkbox :label="item.planName"></el-checkbox><br/>
          </template>
        </el-checkbox-group>
      </div>
    </el-dialog>
    <!--<el-dialog title="添加课程" :visible.sync="centerDialogVisible" width="440px" center>-->
      <!--<el-form :model="registerForm" ref="registerForm" label-width="120px" :rules="rules">-->
        <!--<el-form-item prop="name" label="课程名" size="mini">-->
          <!--<el-input v-model="registerForm.name" placeholder="课程名"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item prop="term" label="学期（天）" size="mini">-->
          <!--<el-input v-model="registerForm.term" placeholder="学期（天）"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="状态" size="mini">-->
          <!--<input type="radio" name="status" value="0" v-model="registerForm.status">&nbsp;启用&nbsp;&nbsp;-->
          <!--<input type="radio" name="status" value="1" v-model="registerForm.status">&nbsp;禁用-->
        <!--</el-form-item>-->
        <!--<el-form-item prop="amount" label="课程金额（元）" size="mini">-->
          <!--<el-input v-model="registerForm.amount" placeholder="课程金额（元）"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item prop="type" label="类型" size="mini">-->
          <!--<el-input v-model="registerForm.type" placeholder="类型"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item prop="parentOperate" label="监护" size="mini">-->
          <!--<el-input v-model="registerForm.parentOperate" placeholder="监护"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item prop="method" label="方式" size="mini">-->
          <!--<el-input v-model="registerForm.method" placeholder="方式（线下，线上）"></el-input>-->
        <!--</el-form-item>-->


      <!--</el-form>-->
      <!--<span slot="footer">-->
                <!--<el-button size="mini" @click="goBack(1)">取消</el-button>-->
                <!--<el-button size="mini" @click="addCourse" type="primary">确定</el-button>-->
            <!--</span>-->
    <!--</el-dialog>-->
    <el-dialog title="添加课程" :visible.sync="centerDialogVisible" width="440px" center>
      <el-form :model="registerForm" ref="registerForm" label-width="120px" :rules="rules1">
        <el-form-item prop="name" label="课程名" size="mini">
          <el-input v-model="registerForm.name" placeholder="课程名"></el-input>
        </el-form-item>
        <el-form-item prop="term" label="学期（天）" size="mini">
          <el-input v-model="registerForm.term" placeholder="学期（天）"></el-input>
        </el-form-item>
        <el-form-item label="状态" size="mini" >
          <label slot="label" class="status_style">状态</label>
          <input type="radio" name="status" value="0" v-model="registerForm.status">&nbsp;启用&nbsp;&nbsp;
          <input type="radio" name="status" value="1" v-model="registerForm.status">&nbsp;禁用
        </el-form-item>
        <el-form-item prop="amount" label="课程金额（元）" size="mini">
          <el-input v-model="registerForm.amount" placeholder="课程金额（元）"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="类型" size="mini">
          <el-input v-model="registerForm.type" placeholder="类型"></el-input>
        </el-form-item>
        <el-form-item prop="parentOperate" label="监护" size="mini">
          <el-input v-model="registerForm.parentOperate" placeholder="监护"></el-input>
        </el-form-item>
        <el-form-item prop="method" label="方式" size="mini">
          <el-input v-model="registerForm.method" placeholder="方式（线下，线上）"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer">
                <el-button size="mini" @click="goBack(1)">取消</el-button>
                <el-button size="mini" @click="addCourse()" type="primary">确定</el-button>
            </span>
    </el-dialog>
    <el-dialog title="修改课程" :visible.sync="editVisible" width="440px" center>
      <el-form :model="form" ref="form" label-width="120px" :rules="rules1">
        <el-form-item prop="name" label="课程名" size="mini">
          <el-input v-model="form.name" placeholder="课程名"></el-input>
        </el-form-item>
        <el-form-item prop="term" label="学期（天）" size="mini">
          <el-input v-model="form.term" placeholder="学期（天）"></el-input>
        </el-form-item>
        <el-form-item label="状态" size="mini">
          <label slot="label" class="status_style">状态</label>
          <input type="radio" name="status" value="0" v-model="form.status">&nbsp;启用&nbsp;&nbsp;
          <input type="radio" name="status" value="1" v-model="form.status">&nbsp;禁用
        </el-form-item>
        <el-form-item prop="amount" label="课程金额（元）" size="mini">
          <el-input v-model="form.amount" placeholder="课程金额（元）"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="类型" size="mini">
          <el-input v-model="form.type" placeholder="类型"></el-input>
        </el-form-item>
        <el-form-item prop="parentOperate" label="监护" size="mini">
          <el-input v-model="form.parentOperate" placeholder="监护"></el-input>
        </el-form-item>
        <el-form-item prop="method" label="方式" size="mini">
          <el-input v-model="form.method" placeholder="方式（线下，线上）"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer">
                <el-button size="mini" @click="goBack(0)">取消</el-button>
                <el-button size="mini" @click="editSave" type="primary">确定</el-button>
            </span>
    </el-dialog>
    <el-dialog title="删除课程" :visible.sync="delVisible" width="400px" center>
      <div align="center">删除不可恢复，是否确定删除课程
        <sapn style="font-size: 18px;color: red;font-weight: bold">{{courseName}}</sapn>
        ？
      </div>
      <span slot="footer">
                <el-button size="mini" @click="delVisible = false">取消</el-button>
                <el-button size="mini" @click="deleteRow" type="primary">确定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCoursePlan,
    bindPlan,
    getCourseList,
    addCourse,
    updateCourse,
    delCourse,
    getByName,
    getPlanList,
    unBinding
  } from '../../api/public/api';
  import {mixin} from '../../../static/js/index';

  export default {
    mixins: [mixin],
    data() {
      var valiNumberPass1 = (rule, value, callback) => {//包含小数的数字
        let reg = /^[+]?(0|([1-9]\d*))(\.[\d+]{1,2})?$/g;
        if (value === '') {
          callback(new Error('请输入内容'));
        } else if (!reg.test(value) || value < 0) {
          callback(new Error('请输入正确的数字（最多两位小数）'));
        } else {
          callback();
        }
      };
      // 学期
      var valiNumber2 = (rule, value, callback) => {
        let reg = /^([1-9]\d*|[0])$/;
        if (value === '') {
          callback(new Error('请输入内容'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确的数字'));
        } else {
          callback();
        }
      };
      //判断课程名是否存在
      const userNameCheck1 = (rule, value, callback) => {
        console.log(value)
        if (value != '') {
            getByName(value).then(res => {
              console.log(res)
            if (res.data.data != 10002) {
              callback(new Error('该用课程名已存在，请重新输入'));
            } else {
              callback();
            }
          })
        } else {
          callback(new Error('请输入课程名'));
        }
      };
      return {
        planList: [],
        isBind: 0,//0,1,绑定 2，解绑
        checkList: [],
        bindVisible: false,
        courseList: [],
        level: 0,
        registerForm: {
          name: "",
          term: "",
          amount: "",
          type: "",
          method: "",
          parentOperate: "",
          status: 0
        },
        id: 0,
        centerDialogVisible: false, //添加弹窗是否显示
        editVisible: false,         //编辑弹窗是否显示
        delVisible: false,          //删除弹窗是否显示
        form: {      //编辑框
          "id": 0,
          "name": "",
          "term": 0,
          "amount": 0,
          "type": "",
          "method": "",
          "parentOperate": "",
          "status": 0
        },
        rules: {
          name: [
            {required: true, validator: userNameCheck1, trigger: 'blur'}
          ],

          term: [
            {required: true, validator: valiNumber2, trigger: 'blur'}
          ],
          amount: [
            {required: true, validator: valiNumberPass1, trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请输入类型', trigger: 'blur'},
          ],
          method: [
            {required: true, message: '请输入方式（线下，线上）', trigger: 'blur'}
          ],
          parentOperate: [
            {required: true, message: '请输入监护', trigger: 'blur'}
          ]
        },
        rules1: {

          name: [
            {required: true, message: '请输入课程名称', trigger: 'blur'}
          ],
          term: [
            {required: true, validator: valiNumber2, trigger: 'blur'}
          ],
          amount: [
            {required: true, validator: valiNumberPass1, trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请输入类型', trigger: 'blur'},
          ],
          method: [
            {required: true, message: '请输入方式（线下，线上）', trigger: 'blur'}
          ],
          parentOperate: [
            {required: true, message: '请输入监护', trigger: 'blur'}
          ]
        },
        courseName: ""
      }
    },

    created() {
      let data = {}
      this.getData(data);
      this.level = localStorage.getItem('level')

    },
    methods: {
      // //表头行的设置
      tableHeaderColor({row,column,rowIndex,columnIndex}){
        return 'background-color:#fff;font-wight:500;font-size:13px;text-align:center;height:50px'
      },
      changeBtn(value) {
        let checkList = localStorage.getItem('checkList').split(',')
        let planName = ''
        console.log(value.length,checkList)
        if (value.length >= checkList.length) {
          //绑定
          this.isBind=false
          for (let i in value) {
            for (let j in checkList) {
              if (value[i] != checkList[i]) {
                planName = value[i]
              }
            }
          }

          this.bindRow(planName)
        } else {
          //  解绑
          this.isBind=true
          let a = value, b = checkList
          let c = [...a, ...b]
          let d = new Set(c)
          let e = Array.from(d)
          planName = [...e.filter(_ => !a.includes(_)), ...e.filter(_ => !b.includes(_))]
          this.$confirm('解绑该方案, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.bindRow(planName)

          }).catch(() => {
            this.getCoursePlan(this.id)
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });

        }
      },
      //查询课程已绑定方案
      getCoursePlan(id) {
        getCoursePlan(id).then(res => {
          if (res.data.code == 0) {
            let data = res.data.data
            let checkList = []
            for (let i in data) {
              checkList.push(data[i].planName)
            }
            this.checkList = checkList
            localStorage.setItem('checkList', checkList)
          }
        })
      },

      getPlanList() {
        let data = {}
        getPlanList(data).then(res => {
          if (res.data.code == 0) {
            this.planList = res.data.data.records
          }
        })
      },
      //绑定方案
      handleBinding(row) {
        this.id = row.id
        this.getPlanList()
        this.getCoursePlan(row.id)
        this.bindVisible = true

      },
      // 绑定 筛选出id
      bindRow(planName) {
        let id = ''
        for (let j in this.planList) {
          if (planName == this.planList[j].planName) {
            id = this.planList[j].id
          }
        }
        this.bindPlans(id)
      },

      bindPlans(data) {
        console.log(data)
        let params = {
          "planId": data,
          "courseId": this.id
        }
        console.log(params)
        if ( this.isBind) {
          //解绑
          unBinding(params).then(res => {
            if (res.data.code == 0) {
              this.notify("解绑成功", "success");
              // this.centerDialogVisible = false;
              this.updateData()
              this.getCoursePlan(this.id)
            } else {
              this.notify("解绑失败", "error");
            }
            // this.bindVisible = false
          })
        } else {
          //绑定
          bindPlan(params).then(res => {
            if (res.data.code == 0) {
              this.notify("绑定成功", "success");
              // this.centerDialogVisible = false;
              this.updateData()
              this.getCoursePlan(this.id)
            } else {
              this.notify("绑定失败", "error");
            }
          })
        }
      },
      //更新数据
      updateData() {
        let data = {}
        this.getData(data);
      },
      //查询所有课程
      getData(data) {
        getCourseList(data).then(res => {
          console.log(res)
          if (res.data.code == 0) {
            let num=1
            res.data.data.records.map(item => {
              // const t = new Date(item.createDate)
              // const y = t.getFullYear()
              // const m = t.getMonth() + 1
              // const d = t.getDate()
              item.num = num++
              //处理小数
              let str = item.amount + ""
              if (str.indexOf(".") != -1) {
                let value2Array = str.split('.');
                let str0 = ""
                if (value2Array[1].length == 1) {
                  str0 = item.amount + "0"
                }
                if (value2Array[1].length == 2) {
                  str0 = item.amount
                }
                if (value2Array[1].length > 2) {
                  str0 = item.amount.toFixed(2)
                }
                item.amount = str0
              } else {
                item.amount = item.amount + ".00"
              }
            })
            this.courseList = res.data.data.records
            console.log(this.courseList)
          }


        })
      },
      //添加课程
      addCourse() {

        this.$refs['registerForm'].validate(valid => {
          if (valid) {
            let params = this.registerForm
            console.log(this.registerForm)
            if (this.registerForm.status == 0) {
              params.status = "启用"
            } else {
              params.status = "禁用"
            }
            addCourse(params)
              .then(res => {
                if (res.data.code == 0) {
                  this.notify("添加成功", "success");
                  this.centerDialogVisible = false;
                  this.updateData()
                } else {
                  this.notify("添加失败", "error");
                }
              })
              .catch(err => {
                console.log(err);
              });
            this.registerForm = {
              "name": "",
              "term": 0,
              "amount": 0,
              "type": "",
              "method": "",
              "parentOperate": "",
              "status": 0
            }
          }
        })

      },
      //弹出编辑页面
      handleEdit(row) {
        this.editVisible = true;
        this.id = row.id
        //查询
        this.form = row
        if (row.status == "启用") {
          this.form.status = 0
        } else {
          this.form.status = 1
        }
      },
      //保存编辑页面修改的数据
      editSave() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            let params = this.form
            console.log(this.form)
            if (this.form.status == 0) {
              params.status = "启用"
            } else {
              params.status = "禁用"
            }
            updateCourse(params)
              .then(res => {
                if (res.data.code == 0) {
                  this.editVisible = false;
                  this.updateData();
                  this.notify("修改成功", "success");
                } else {
                  this.notify("修改失败", "error");
                }
              })
              .catch(err => {
                console.log(err);
              });
          }
        })

      },
      //取消
      goBack(i) {
        if (i == 1) {
          this.registerForm = {
            name: "",
            term: 0,
            amount: 0,
            type: "",
            method: "",
            parentOperate: "",
            status: 0
          }
          this.centerDialogVisible = false
        } else {
          this.centerDialogVisible = false;
          this.updateData();
        }


      },
      handleDelete(row) {
        this.courseName = row.name
        this.id = row.id
        this.delVisible = true;
      },
      //删除
      deleteRow() {
        let params = {
          "id": this.id
        }
        delCourse(this.id)
          .then(res => {
            if (res.data.code == 0) {
              this.delVisible = false;
              this.updateData();
              this.notify("删除成功", "success");
            } else {
              this.notify("删除失败", "error");
            }
          })
          .catch(err => {
            console.log(err);
          });

      }

    },
    mounted(){
      // setTimeout(function () {
      //   this.addCourse()
      // },3000)

      // //表头行的设置
      // tableHeaderColor({row,column,rowIndex,columnIndex}){
      //   return 'background-color:#fff;font-wight:500;font-size:13px;text-align:center;height:50px'
      // }

    }
  }
</script>
<style>
  .el-form-item__label{
    text-align: left;
    width: 60px;
    padding-left: 5px;
    line-height: 0px;
  }
</style>
<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }
  .consumer-img {
    width: 100%;
    height: 80px;
    border-radius: 5px;
    margin-bottom: 5px;
    overflow: hidden;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .pagination {
    display: flex;
    justify-content: center;
  }
.status_style{
  padding-left: 10px;
}


</style>
